#!/bin/python3.6
import json
import random
import re
import string
import logging
import requests

from Scripts.search import search_user
from Scripts.mess import send_mess
from Scripts.headers import config, jira_headers, log_format
from Scripts.ldap import LdapAction
from Scripts.mysql import MysqlConn


def random_passwd():  # 随机生成密码
    # 密码强度为10位符号、字母、数字混合
    return "!" + "".join(random.sample(string.ascii_letters + string.digits + ',.', 9))


class Api:
    def __init__(self, en_name, user_id, employee_type=1):
        logging.basicConfig(level=logging.WARNING,
                            format=log_format)

        self.headers = jira_headers
        self.url = config.get("jira", "ip")

        # 根据飞书查询用户，返回user_json
        self.user_json = search_user(user_id)
        self.user_json["user_id"] = user_id
        self.user_json["password"] = random_passwd()
        self.user_json['employee_type'] = employee_type
        self.user_json['employeeNumber'] = 1

        # 创建jira用户创建所需要的json
        self.jira_create_list = {
                                        "name": self.user_json["name_pinyin"],
                                        "password": self.user_json['password'],
                                        "emailAddress": self.user_json['emailAddress'],
                                        "displayName": en_name
                                }

        # 如果传入的name_pinyin为test用户，自动变更为测试用户
        if self.user_json['name_pinyin'] == config.get("test", "user_name"):
            self.user_json['name_pinyin'] = 'test'
            self.user_json['displayName'] = 'test'
        logging.warning(f'API获得的user数据为：{json.dumps(self.user_json, indent=4, ensure_ascii=False)}')
        self.LdapAction = LdapAction(user_id=user_id,
                                     password=self.user_json["password"],
                                     user_json=self.user_json)

    def password_change(self, active_type=None):
        password_change = {"password": self.user_json["password"]}
        password_change_url = '%s/rest/api/2/user/password?username=%s' % (self.url, self.user_json["name_pinyin"])
        result = requests.put(password_change_url, data=json.dumps(password_change), headers=self.headers)

        # 当active_type传参不为空且jira中用户不存在，创建用户
        if active_type and re.search(r'用户“(.*)”不存在', result.text):
            self.jira_user_add(active_type='quiet_add')
        elif active_type == 'dis':
            self.LdapAction.change_ldap_password(have_samba=True, disable=True)
        else:
            self.LdapAction.change_ldap_password(have_samba=True)
        if active_type != "dis" or active_type is None:
            send_mess(action_type="change_password", user_json_input=self.user_json)

        logging.warning(f'消息发送：{result.text},新密码为：{password_change["password"]}')

    def user_disable(self):
        self.password_change(active_type="dis")
        disable_user = dict()
        disable_user['active'] = 'false'  # jira用户禁用
        disable_user_url = '%s/rest/api/2/user?username=%s' % (self.url, self.user_json["name_pinyin"])
        requests.put(disable_user_url, data=json.dumps(disable_user), headers=self.headers)
        self.LdapAction.change_ldap_password(have_samba=True)
        send_mess(action_type="disable_user", user_json_input=self.user_json)

    def jira_user_search(self):  # 0810新增
        search_jira = requests.get(url='%s/rest/api/2/user?username=%s' % (self.url, self.user_json["name_pinyin"]),
                                   headers=self.headers)
        return json.loads(search_jira.text)['displayName']

    def jira_user_add(self, active_type=None):  # 调用jira模块添加用户
        self.jira_create_list["name"] = self.user_json['name_pinyin']
        create_user_url = '%s/rest/api/2/user' % self.url  # 拼接URL
        m = requests.post(create_user_url, data=json.dumps(self.jira_create_list),
                          headers=self.headers)  # 发送创建请求
        logging.warning(f'{m.text}')
        try:
            create_result = json.loads(m.text)["errors"]
            if create_result:
                if self.LdapAction.search_ldap_userid() is False:
                    logging.warning(f'{self.jira_create_list["displayName"]},用户名以存在，创建失败。')
                    send_mess(action_type='create_false', user_json_input=self.user_json)  # 发送消息给相关群
                return False
        except Exception as e2:
            if e2 != 'errors':
                logging.warning(f'{e2}')
            logging.warning(f'{self.jira_create_list["displayName"]},创建成功。')
            self.user_json['name_pinyin'] = self.jira_create_list['name']
            self.LdapAction.ldap_samba(comm_type="MODIFY_ADD")
            mysql = MysqlConn()
            mysql.insert(user_json=self.user_json)
            if active_type != 'quiet_add':
                send_mess(action_type='create_true', user_json_input=self.user_json)  # 发送消息给新建账户
